package com.studentstreet;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.studentstreet.adapter.OrderAdapter;
import com.studentstreet.component.LwtAlertDialog;
import com.studentstreet.component.LwtAlertDialog.Builder;
import com.studentstreet.entities.OrderEntity;
import com.studentstreet.entities.UserEntity;
import com.studentstreet.tools.HttpHelper;
import com.studentstreet.tools.PreferenceTools;
import com.studentstreet.tools.Util;
import com.studentstreet.tools.Utility;
import com.studentstreet.tools.dbhelper.OrderDBHelper;
import com.studentstreet.tools.dbhelper.UserDBHelper;

/**
 * @author likebamboo
 * 
 */
public class OrderActivity extends Activity implements OnGestureListener {
	// Title标题
	private TextView titleText;
	// Login Button登录按钮
	private Button login_bt;
	// 头部左边的按钮
	private ImageButton backImgBt = null;
	// 改变订单信息按钮
	private Button orderChangeButton = null;
	// 订单详情按钮
	private Button orderDetailButton = null;
	// 订单详情列表
	private ListView orderListView = null;

	// 修改送餐信息按钮
	private Button delivertChangeButton = null;
	// 送餐地址
	private EditText deliveryAddrEdit = null;
	// 领餐人
	private EditText deliveryUserEdit = null;
	// 期望送达时间
	private EditText deliveryTimeEdit = null;
	// 提交按钮
	private Button commitButton = null;
	// 订单详情是否处于显示状态
	private int orderDetailShow = View.VISIBLE;
	// 显示订单详情动画效果
	private Animation animIn = null;
	// 隐藏订单详情动画效果
	private Animation animOut = null;
	// 订单状态数组
	String[] orderState = null;
	// 订单总价格
	double priceAll = 0d;
	// 订单总数量
	int countAll = 0;

	// 标志EditText是否可编辑
	boolean isEditEnable = false;
	// 标志送货信息下载完成
	private final static int DELIVERY_MSG = 1;

	// 资源
	private Resources res = null;
	// 用于将个人数据保存到数据库
	private UserDBHelper dbHelper = null;
	// 用户实体
	private UserEntity user = null;
	// 用户名，用于提交到服务器
	private String userName = "";
	// 标志提交到服务器的是订单提交数据
	private final static String ORDER_COMMIT = "order_commit";
	// 用于取得用户数据
	private PreferenceTools prefTools = null;

	// OEM++ 侧边栏菜单的手势效果 @ 2013-1-15
	private GestureDetector gestureDetector;

	// OEM--

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.order);
		// 将当前Activity压入堆栈中
		MyApp.getInstance().addActivity(this);
		dbHelper = new UserDBHelper(this);
		// OEM++侧边菜单栏
		gestureDetector = new GestureDetector(this);
		// OEM--
		// 初始化头部
		initHeader();
		res = getResources();
		// 订单详情
		orderChangeButton = (Button) findViewById(R.id.order_changeBt);
		orderDetailButton = (Button) findViewById(R.id.order_detail_bt);
		orderListView = (ListView) findViewById(R.id.order_detail_list);
		// 送货信息
		delivertChangeButton = (Button) findViewById(R.id.order_deliveryBt);
		deliveryAddrEdit = (EditText) findViewById(R.id.order_delivery_addr);
		deliveryUserEdit = (EditText) findViewById(R.id.order_delivery_user);
		deliveryTimeEdit = (EditText) findViewById(R.id.order_delivery_time);
		// 提交按钮
		commitButton = (Button) findViewById(R.id.order_commit);
		// 动画效果
		animIn = AnimationUtils.loadAnimation(this, R.anim.slide_up_in);
		animOut = AnimationUtils.loadAnimation(this, R.anim.slide_down_out);
		// 为订单按钮添加动画效果
		orderDetailButton.setOnClickListener(new MyOnClickListener(
				orderDetailShow, orderListView));

		orderChangeButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		delivertChangeButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				isEditEnable = !isEditEnable;
				// 设置编辑框的样式
				SetEditStyle(isEditEnable);
				// 获得焦点
				deliveryAddrEdit.requestFocus();
			}
		});
		commitButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 提交订单时的进度对话框
				ProgressDialog commitPro = new ProgressDialog(
						OrderActivity.this);
				// 启动提交订单异步任务
				CommitOrderAsync commitOrderAsync = new CommitOrderAsync(
						commitPro);
				commitOrderAsync.execute("");
			}
		});
		// 取得用户信息
		prefTools = new PreferenceTools(this);
		userName = prefTools.getUserName();
		// 查询当前数据库是否有该用户的数据,如果有，则从本地加载数据
		user = dbHelper.getUser(userName);
		if (!"".equals(user.getName())) {
			initDeliverMsg();
		} else {
			// 启动加载送货信息线程，加载送货信息
			Thread userMsg = new Thread(new UserMsgThread());
			userMsg.start();
		}
	}

	// 初始化送货信息
	private void initDeliverMsg() {
		deliveryAddrEdit.setText(user.getAddr());
		deliveryUserEdit.setText(user.getName() + "  [" + user.getTel() + "]");
		deliveryTimeEdit.setText(res.getString(R.string.one_hour));
	}

	// 初始化头部信息
	private void initHeader() {
		// 返回按钮
		backImgBt = (ImageButton) findViewById(R.id.header_imgBt);
		// 头部中间的标题
		titleText = (TextView) findViewById(R.id.title);
		// 登录按钮
		login_bt = (Button) findViewById(R.id.login_bt);
		// 返回按钮
		backImgBt.setImageResource(R.drawable.back);
		backImgBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		// 头部中间的标题
		titleText.setText(getResources().getString(R.string.order));
	}

	// 设置编辑框的可编辑性、背景等样式
	private void SetEditStyle(boolean flag) {
		// 设置是否可编辑
		deliveryAddrEdit.setEnabled(flag);
		deliveryTimeEdit.setEnabled(flag);
		deliveryUserEdit.setEnabled(flag);
		// 获取背景图片与按钮的文字
		Drawable editBg = res.getDrawable(R.drawable.order_edit_bg);
		String editBtStr = res.getString(R.string.edit);
		if (flag) {
			editBg = res.getDrawable(R.drawable.edit_bg);
			editBtStr = res.getString(R.string.sure);
		}
		// 改变编辑框的背景
		delivertChangeButton.setText(editBtStr);
		deliveryAddrEdit.setBackgroundDrawable(editBg);
		deliveryTimeEdit.setBackgroundDrawable(editBg);
		deliveryUserEdit.setBackgroundDrawable(editBg);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.arg1) {
			case DELIVERY_MSG:
				// 初始化送货信息
				initDeliverMsg();
				break;
			default:
				break;
			}

		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		// 理论上讲，进入到该页面肯定是已经登录过的的用户，所以其实下面这条语句没用 // 判断是否已经登录
		if (!prefTools.isLogin()) {
			return;
		}
		// 取得用户信息
		userName = prefTools.getUserName();
		if (!userName.equals("")) {
			login_bt.setText(userName);
			// 去掉登录按钮文本右边的图标
			login_bt.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
					null);
		}
		// 实时加载订单信息
		OrderAdapter adapter = new OrderAdapter(this, userName);
		orderListView.setAdapter(adapter);
		Utility.setListViewHeightBasedOnChildren(orderListView);
		// 加载订单统计信息
		OrderDBHelper dbHelper = new OrderDBHelper(this);
		countAll = dbHelper.getCountTotal(userName);
		priceAll = dbHelper.getPriceTotal(userName);
		orderState = res.getStringArray(R.array.order_state);
		orderDetailButton.setText(res.getString(R.string.order_total, priceAll,
				countAll, orderState[0]));

	}

	// 加载用户送货信息线程
	class UserMsgThread implements Runnable {
		@Override
		public void run() {
			String json = "";
			// 使用apache HTTP客户端实现
			String urlStr = Util.BASE_URL + "/servlet/UserServlet";
			// 创建网络连接工具对象
			HttpHelper helper = new HttpHelper(urlStr);
			// 添加参数
			// 用户名
			helper.addParam("user_name", userName);
			// 获得服务器返回的数据
			json = helper.getResponse();
			// 获得的用户数据为空
			if ("".equals(json)) {
				return;
			}
			// 将用户Json数据转化为实体对象
			Gson gson = new Gson();
			user = gson.fromJson(json, UserEntity.class);
			// 将数据保存到数据库中
			dbHelper.saveToDB(json);

			// 新建消息并发送
			Message msg = handler.obtainMessage();
			msg.arg1 = DELIVERY_MSG;
			handler.sendMessage(msg);
		}
	}

	// 按钮点击事件监听器(动画效果)
	class MyOnClickListener implements View.OnClickListener {
		private int flag;
		private View view;

		public MyOnClickListener(int flag, View view) {
			super();
			this.flag = flag;
			this.view = view;
		}

		@Override
		public void onClick(View v) {
			if (flag == View.VISIBLE) {
				flag = View.GONE;
				animOut.setAnimationListener(new MyAnimationListener(view));
				view.startAnimation(animOut);
			} else {
				flag = View.VISIBLE;
				view.startAnimation(animIn);
				view.setVisibility(flag);
			}
		}

	}

	// 异步任务将订单数据上传到服务器
	class CommitOrderAsync extends AsyncTask<String, ProgressDialog, String> {
		ProgressDialog pd = null;
		String json = "";

		public CommitOrderAsync(ProgressDialog pd) {
			super();
			this.pd = pd;
		}

		@Override
		protected String doInBackground(String... params) {
			// 使用apache HTTP客户端实现
			String urlStr = Util.BASE_URL + "/servlet/OrderServlet";
			// 创建网络连接工具对象
			HttpHelper helper = new HttpHelper(urlStr);
			// 添加参数
			// 用户名
			helper.addParam("request", ORDER_COMMIT);
			helper.addParam("order", json);
			helper.addParam("userName", userName);
			helper.addParam("toAddr", getToAddr());
			helper.addParam("toUser", getToUser());
			helper.addParam("toTime", getToTime());
			// 获得服务器返回的数据
			json = helper.getResponse();
			return json;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pd.cancel();
			// 任何数据都没返回，说明网络有问题，显示提示信息
			if ("".equals(result)) {
				showMsg(R.string.cannot_arrived_server);
				return;
			}
			// 服务器端操作失败
			if ("ERROR".equals(result)) {
				showMsg(R.string.commit_order_failed);
				return;
			}

			// 操作成功，将数据保存到order表
			OrderEntity order = new OrderEntity();
			order.setDetail(OrderDBHelper.ORDETAIL);
			order.setNo(result);
			order.setTime(Util.orderNo2String(result));
			order.setToAddr(getToAddr());
			order.setToTime(getToTime());
			order.setToUser(getToUser());
			order.setState(1);
			OrderDBHelper dbHelper = new OrderDBHelper(OrderActivity.this);
			dbHelper.saveOrder(order, userName);
			// 修改订单项状态
			dbHelper.setOrderState(result, userName);

			// 显示对话框
			final Intent intent = new Intent();
			LwtAlertDialog.Builder builder = new Builder(OrderActivity.this);
			builder.setTitle(res.getString(R.string.commit_order_success))
					.setMessage(res.getString(R.string.choose))
					.setPositiveButton(res.getString(R.string.continue_shop),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 回到主页
									intent.setClass(OrderActivity.this,
											MainActivity.class);
									startActivity(intent);
									finish();
								}
							})
					.setNegativeButton(res.getString(R.string.check_order),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 跳转到订单跟踪页面
									intent.setClass(OrderActivity.this,
											OrderTrackActivity.class);
									startActivity(intent);
									finish();
								}
							}).show();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// 显示提交订单进度框
			pd.setMessage(res.getString(R.string.committing));
			pd.show();
			// 获得加密后的订单数据
			OrderDBHelper dbHelper = new OrderDBHelper(OrderActivity.this);
			json = dbHelper.getOrderJson(userName);
		}

		@Override
		protected void onProgressUpdate(ProgressDialog... values) {
			super.onProgressUpdate(values);
		}

	}

	// 得到送餐地址
	private String getToAddr() {
		return deliveryAddrEdit.getText().toString();
	}

	// 得到期望送餐时间
	private String getToTime() {
		return deliveryTimeEdit.getText().toString();
	}

	// 得到接餐人
	private String getToUser() {
		return deliveryUserEdit.getText().toString();
	}

	// 显示网络操作提示信息
	private void showMsg(int resId) {
		Toast.makeText(this, res.getString(resId), Toast.LENGTH_LONG).show();
	}

	// 动画类
	class MyAnimationListener implements AnimationListener {
		private View v;

		public MyAnimationListener(View v) {
			super();
			this.v = v;
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			v.setVisibility(View.GONE);
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}

		@Override
		public void onAnimationStart(Animation animation) {
		}

	}

	// OEM++手势滑动 李文涛@2013-1-15
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	/**
	 * 用户按下触摸屏、快速移动后松开
	 */
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.i("MyGesture", "onFling");

		final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;
		if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
			// Fling right
			LeftMenu.prepare(OrderActivity.this, R.id.order_layout);
			startActivity(new Intent(OrderActivity.this, LeftMenu.class));
			overridePendingTransition(0, 0);
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	public boolean onTouch(View v, MotionEvent event) {
		return gestureDetector.onTouchEvent(event);
	}

	/**
	 * 解决ScrollView后不执行左右移动监听事件OnGestureListener
	 * 在Activity中添加ScrollView实现滚动activity的效果后，activity的滑动效果却无法生效了
	 * 原因是因为activity没有处理滑动效果，重写以下方法即可解决。
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		gestureDetector.onTouchEvent(ev);
		return super.dispatchTouchEvent(ev);
	}

	// OEM --

	// OEM++ 2013-02-27 监听菜单按钮事件，实现与手势相同的滑动效果
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		LeftMenu.prepare(OrderActivity.this, R.id.order_layout);
		startActivity(new Intent(OrderActivity.this, LeftMenu.class));
		overridePendingTransition(0, 0);
		return false;
	}
	// OEM--

}
